<?php
include_once("../include/common.inc.php");
include_once ('magick.php');


$gid = 0;
$v_percent = null;
$width = 200;
$height = 200;

$var = $_POST['elements'];
$var1 = urldecode($var);
$var2 = str_replace("\\", "", $var1);;
$var3 = json_decode($var2);
$var4 = (array)$var3;
foreach($var4 as $d){
    if($d->type == 'cal'){
        $gid = $d->gid;
        $v_percent = $d->percentw;
        // 取日历文件
        $cal = NewMagickWand();
        MagickReadImage ( $cal, '..'.$d->url );
        // 取日历宽高
        $height = MagickGetImageHeight($cal);
        //echo var_dump($height);
        $width = MagickGetImageWidth($cal);
        //echo var_dump($width);

    }
}

// 新建场景以日历宽高为准
$dst = NewMagickWand();
MagickNewImage($dst, (integer)$width, (integer)$height);

foreach($var4 as $d){
    if($d->type == 'pho'){
        $src = NewMagickWand();
        MagickReadImage($src, "..".$d->url);
        $w1 = MagickGetImageWidth($src);
        $h1 = MagickGetImageHeight($src);
        MagickScaleImage($src, $w1*(1+$v_percent), $h1*(1+$v_percent));
        //MagickScaleImage($src, $w1, $h1);
        MagickSetImageIndex($src,0);// index
        MagickCompositeImage($dst,$src,MW_OverCompositeOp,($d->x)*(3+$v_percent),($d->y)*(3+$v_percent)); //position
        MagickAddImage( $dst, $src );
        //echo $d->x.' => '.(($d->x)*(1+$v_percent));
        //echo '\n';
        //echo $d->y.' => '.(($d->y)*(1+$v_percent));
    }
}

MagickSetImageIndex($cal,1);
MagickCompositeImage($dst,$cal,MW_OverCompositeOp,0,0);
MagickAddImage( $dst, $cal );

MagickSetFormat($dst, 'PNG');

if(isset($_COOKIE['DedeUserID'])){
    $uid = $_COOKIE['DedeUserID'];
    $path = '../uploads/finished/'.$uid.'/'.$gid.'/';
    $dir1 = '../uploads/finished/'.$uid;
    if(!is_dir($dir1)){
        mkdir($dir1);
        //echo 'mkdir is ok';
    }
    $dir2 = '../uploads/finished/'.$uid.'/'.$gid;
    if(!is_dir($path)){
        mkdir($path);
        //echo 'mkdir is ok';
    }
    $filename = $path.time().'.png';
}else{
    $path = '../uploads/finished/0/'.$gid.'/';
    $dir1 = '../uploads/finished/0/'.$gid;
    if(!is_dir($path)){
        mkdir($path);
        //echo 'mkdir is ok';
    }
    $filename = $path.time().'.png';
}


MagickWriteImage($dst, $filename);

$db_filename = substr($filename, 2);
//echo var_dump($db_filename);
$inquery = "INSERT INTO `fmcalendar`(uid,url,width,height,memo,gid,gname)
            VALUES('$uid','$db_filename','$width','$hight','$memo','$gid','$gname')";
    $re = $dsql->ExecuteNoneQuery($inquery);
    //echo var_dump($uploadpath);
    if($re){
        echo 'OK';
    }else{
        echo 'FALSE';
    }

?>